import React from "react";
import { Radio, message } from "antd";
import { fromJS } from "immutable";
const RadioGroup = Radio.Group;
declare let window: any;
const { msg } = window.xDllContext;
import { SortableContainer, SortableElement, arrayMove } from "react-sortable-hoc";
const SortableItem = SortableElement(({ name, replaceImg, total, onClickDel }) => (
  <li>
    <p>{name}</p>
    <span className="li-brand">
      <i className="x-site-new-qIcon brand" onClick={replaceImg} />
    </span>
    {total > 1 && (
      <span className="li-del">
        <i className="x-site-new-qIcon del " onClick={onClickDel} />
      </span>
    )}
  </li>
));

const SortableList = SortableContainer(({ items, onClickDel, replaceImg, onAddVideo }) => {
  const list: any[] = [];
  fromJS(items)
    .toJS()
    .map((item, index) => {
      return list.push(
        <SortableItem
          key={`item-${index}`}
          index={index}
          name={item.name}
          total={items.length}
          onClickDel={() => onClickDel(index)}
          replaceImg={event => replaceImg(index, event)}
        />
      );
    });
  return (
    <ul>
      {list}
      {items.size < 20 && (
        <li className="ad-screen-add-video" onClick={onAddVideo}>
          +添加
        </li>
      )}
    </ul>
  );
});

export default class AdScreenTopEdit extends React.Component<any, any> {
  constructor(props) {
    super(props);
    const { style } = this.props;
    this.state = {
      splitScreen: style.get("splitScreen"),
      playType: style.get("playType")
    };
  }
  static defaultProps = {};
  render() {
    const { items, style } = this.props;
    return (
      <div className="ad-screen-top-edit">
        <div>
          <p className="edit-style">
            <span className="edit-style-lf">分屏样式：</span>
            <span className="edit-style-rt">（不同样式视频上传后会进行不同的裁剪）</span>
          </p>
          <p className="edit-video-list">
            <span className="edit-video-list-lf">播放列表：</span>
            <span className="edit-video-list-rt">（最多上传20）</span>
          </p>
        </div>
        <SortableList
          items={items}
          onSortEnd={this.onSortEnd}
          axis="y"
          hideSortableGhost={false}
          useWindowAsScrollContainer={true}
          shouldCancelStart={e => e.target.classList.contains("x-site-new-qIcon")}
          onClickDel={this.onClickDel}
          replaceImg={this.replaceImg}
          onAddVideo={this.onAddVideo}
        />
        <span className="edit-message">
          视频比例：16：9，建议分辨率：
          <span style={{ fontWeight: "bold" }}>960*540、1280*720、1366*768；</span>
          <br />
          视频格式支持：mp4，每个不能超过200Mb
        </span>
      </div>
    );
  }
  onSplitScreen = e => {
    const value = e.target.value;
    this.setState({
      splitScreen: value
    });
    this._changeVal(["props", "top", "style", "splitScreen"], value, null);
  };

  replaceImg = index => {
    const videoSrcPath = ["props", "top", "items", index, "src"];
    const videoNamePath = ["props", "top", "items", index, "name"];
    msg.emit("edit:chooseImage", {
      __data_info: this.props.__info ? this.props.__info.get(videoSrcPath.join(",")) : null,
      fileType: "video",

      changeVal: chooseImageInfo => {
        const videoSrc = chooseImageInfo.info.src;
        const videoName = chooseImageInfo.info.name;
        const isImg = /.(jpeg|jpg|gif|png)$/i.test(videoSrc);
        if (isImg) {
          message.error("请选择视频格式");
          return;
        }
        this.props.onMultiDataChange([
          { path: videoSrcPath, value: videoSrc },
          { path: videoNamePath, value: videoName }
        ]);
      }
    });
  };
  onClickDel = index => {
    const itemsPath = ["props", "top", "items"];
    let { items } = this.props;
    items = items.delete(index);
    this._changeVal(itemsPath, items, null);
  };
  onAddVideo = () => {
    const itemsPath = ["props", "top", "items"];
    let { items } = this.props;
    msg.emit("edit:chooseImage", {
      __data_info: this.props.__info ? this.props.__info.get(itemsPath.join(",")) : null,
      fileType: "video",
      changeVal: chooseImageInfo => {
        const videoSrc = chooseImageInfo.info.src;
        const name = chooseImageInfo.info.name;
        const list = {
          src: videoSrc,
          href: "#",
          name
        };
        items = items.push(list);
        const isImg = /.(jpeg|jpg|gif|png)$/i.test(videoSrc);
        if (isImg) {
          message.error("请选择视频格式");
          return;
        }
        this._changeVal(itemsPath, items, chooseImageInfo);
      }
    });
  };
  // 拖拽组件嵌入
  onSortEnd = ({ oldIndex, newIndex }) => {
    const { __info, compConfig } = this.props;

    if (oldIndex === newIndex) return;
    const changedData: any = [];
    const items = this.props.items.toJS();
    const data = arrayMove(items, oldIndex, newIndex);
    changedData.push({
      path: ["props", "top", "items"],
      value: fromJS(data)
    });

    if (__info) {
      changedData.push({
        path: ["__info"],
        value: this.swapInfo(oldIndex, newIndex)
      });
    }

    this.props.onMultiDataChange(changedData);
  };
  /**
   * 交换__info数据
   * @desc  交换__info下存储位置,否则交换顺序会引起数据错乱
   * @param oldIndex  {Number}
   * @param newIndex {Number}
   */
  swapInfo(oldIndex, newIndex) {
    let { __info } = this.props;
    if (!__info) return null; // 不需要交换
    const current = ["props", "top", "items", newIndex, "src"].join(",");
    const target = ["props", "bottom", "items", oldIndex, "src"].join(",");
    __info = __info.set(current, __info.get(target)).set(target, __info.get(current));
    __info = __info.filter(item => !!item); // 过滤掉undefined
    return __info;
  }

  _changeVal = (pathArray, newVal, platFormValueMap) => {
    this.props.onDataChange(pathArray, newVal, platFormValueMap);
  };
}
